<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BAppUI
 *
 * @author ID59C
 */
class BUIApp extends BUINode {

    const LEFTMENU = "leftmenu";
    const MAINMENU = 'mainmenu';
    const PC_BOOTSTRAPE = 'pc_bootstrap';
    const MOBILE_BOOTSTRAPE = 'm_bootstrap';
    const TABLET_BOOTSTRAPE = 't_bootstrap';
    const DEVICE_IPHONE = 'iphone';
    const DEVICE_IPAD = "ipad";
    const DEVICE_ANDROID_TABLET = 'android_tablet';
    const DEVICE_MOBILE_GENERAL = "mobile_general";
    const DEVICE_TABLET_GENERAL = "tablet_general";
    const DEVICE_ANDROID = 'android';
    const HomeNode_PersonalService = 'home_node_personal_service';

    protected $theme = null;
    protected $startScreen = null;
    protected $startScreenFlow = null;
    public $layoutView = null;
    public $views = null;
    private $mySpaceLinkBeforeSend = null;
    private $myServicesLinkBeforeSend = null;

    public function __construct($node = NULL) {
        parent::__construct($node);
        $this->node = $node;

        if ($this->theme == NULL)
            $this->setTheme(self::PC_BOOTSTRAPE);

        $this->formPath = $this->node->uiPath . ".themes." . $this->theme . ".forms";
        $this->viewPath = $this->node->uiPath . ".themes." . $this->theme . ".views";
    }

    public function setTheme($theme) {
        if ($theme != NULL) {
            $this->theme = $theme;
        }
    }

    public function getTheme() {

        if ($this->theme != NULL)
            return $this->theme;
    }

    public function getName() {
        return 'bieleen.com';
    }

    public function renderLogin() {
        $controller = Yii::app()->getController();

        $form = $this->getFormByMeta("Login");
        $signForm = $this->getFormByMeta("Signup");

        $loginModel = null;
        $renderLogin = true;

        if ($form->submitted("login") && $form->validate()) {
            $loginModel = $form->getModel();
            $loginModel->login();
            //$homeUrl = Blyn::app()->getAppUI()->getHomeUrl();
            Blyn::app()->getAppUI()->renderApp(BUIApp::HomeNode_PersonalService);
            //$controller->redirect($homeUrl);
        }

        if ($form->submitted("signup")) {
            //  $controller->redirect(array("site/signup"));
            $renderLogin = FALSE;
            $controller->layout = "//layouts/column1";
            $controller->render("showOneForm", array('form' => $signForm));
        }

        if ($signForm->submitted("signup")) {
            $renderLogin = FALSE;
            if ($signForm->validate()) {

                $model = $signForm->getModel();

                if ($model->signUp()) {
                    $loginModel = new LoginFormModel();
                    if ($loginModel->login($model->email, $model->password)) {
                        //$controller->redirect($homeUrl);
                        Blyn::app()->getAppUI()->renderApp(BUIApp::HomeNode_PersonalService);
                    }
                }
            }
            $controller->layout = "//layouts/column1";
            $controller->render("showOneForm", array('form' => $signForm));
        }

        if ($renderLogin) {
            $controller->layout = "//layouts/column1";
            $controller->render('showOneForm', array('form' => $form));
        }
    }

    public function renderApp($data = NULL) {
        Blyn::app()->setContext($data);
        Blyn::app()->getCurrentNode()->getUIManager()->renderNode();
        //$this->render();
    }

    public function render($data = null) {

        if (isset($_REQUEST['myServicesLink'])) {
            $screen = $this->getScreen('BScreenMyServices');
            $this->setCurrentScreen($screen);
        }
        else        //by default, render personalservice as home        
            Blyn::app()->getCurrentUser()->getPersonalService()->getUIManager()->render();


        /*
          $this->layoutView = 'appLayout';

          $screen = $this->currentScreen = $this->getScreen('BScreenIndex');

          $screen->render($data);
         * 
         */

        //       $this->gotoScreen($screen, $data);
    }

    public function getLayoutView() {

        if ($this->layoutView == NULL)
            $this->layoutView = 'appLayout';

        return $this->layoutView;
    }

    public function getViews() {

        /*
          if ($this->currentScreen != NULL) {
          $screen = $this->getCurrentScreen();
          $this->addRenderView('screenView', $screen->getLayoutView(), array('uiObj' => $screen));
          }
         * 
         */

        return $this->views;
    }

    protected function registerMenu($event) {

        parent::registerMenu($event);

        $menuManager = $this->getMenuManager();
      
        $mySpaceLinkBeforeSend = 'function(){
                $("ul.nav li.active").removeClass("active");
                $("li:contains(\'My Space\')").addClass("active");
                }';
        $this->mySpaceLinkBeforeSend = $mySpaceLinkBeforeSend;

        $myServicesLinkBeforeSend = 'function(){
                $("ul.nav li.active").removeClass("active");
                $("li:contains(\'My Services\')").addClass("active");
                }';
        $this->myServicesLinkBeforeSend = $myServicesLinkBeforeSend;

        $mainMenu = array(
            'items' => array(
                'mySpace' => array('label' => 'My Space', 'url' => array('site/index'), 'ajaxUrl' => $this->getHomeUrl(array('ajaxLink' => array('name' => 'My Space', 'ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend))))),
                'serviceStore' => array('label' => 'Service Store', 'url' => array('site/serviceStore')),
                'myServices' => array('label' => 'My Services', 'ajaxUrl' => $this->getUrl(array('ajaxLink' => array('name' => 'My Services', 'ajaxOptions' => array('beforeSend' => $myServicesLinkBeforeSend, 'data' => array('myServicesLink' => TRUE)))))),
                'logOut' => array('label' => 'logout(' . Yii::app()->user->name . ')',
                    'url' => array('/site/logout'))));

        $serviceStoreLinkBeforeSend = 'function(){
                $("ul.nav li.active").removeClass("active");
                $("li:contains(\'Service Store\')").addClass("active");
                }';       

        $menuManager->addMenu(self::MAINMENU, $mainMenu);        

        $savedLeftMenu = $menuManager->getMenu(self::LEFTMENU);

        //$leftMenu = $savedLeftMenu;

        $app = Blyn::app();
        $pService = $app->getCurrentUser()->getPersonalService();
        $psApps = $pService->getServiceEngine()->doOperation(BServiceEngine::GETSERVICEAPPSOPERATION, array('Service' => $pService));
        //$psApps = $pService->getServiceApps();
        //add unchange menu into transit variable and get only from saved menu
        $savedLeftMenu = NULL;
        if ($savedLeftMenu == NULL || (isset($savedLeftMenu['items'])&&$savedLeftMenu['items']) == NULL) {

            $leftMenu = array('items' => array());
            //$menuManager->addMenuItem($leftMenu, array('label' => 'My Space'));

            foreach ($psApps as $sApp) {
                if (get_class($sApp) == "BPersonalApp") {
                    $oppCreateUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_CREATESERVICE)->getUIManager()->getUrl();
                    $oppCreateAjaxUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_CREATESERVICE)->getUIManager()->getUrl(array('ajaxLink' => array('name' => 'creat a service', 'ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend))));
                    $menuManager->addMenuItem($leftMenu, array('label' => 'create a service', 'ajaxUrl' => $oppCreateAjaxUrl,
                        'url' => $oppCreateUrl));

                    //$oppJoinUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_JOINSERVICE)->getUIManager()->getUrl();
                    //$oppJoinAjaxUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_JOINSERVICE)->getUIManager()->getUrl(array('ajaxLink' => array('name' => 'join a service', 'ajaxOptions' => array('beforeSend' => $serviceStoreLinkBeforeSend))));
                    $serviceStoreAjaxUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_JOINSERVICE)->getUIManager()->getUrl(array('ajaxLink' => array('name' => 'Service Store', 'ajaxOptions' => array('beforeSend' => $serviceStoreLinkBeforeSend))));
                    $mainMenu = Blyn::app()->getAppUI()->getMenu(BUIApp::MAINMENU);
                    $mainMenu['items']['serviceStore'] = array('label' => 'Service Store', 'url' => array('site/serviceStore'), 'ajaxUrl' => $serviceStoreAjaxUrl);
                    $menuManager->addMenu(self::MAINMENU, $mainMenu);
                    //$menuManager->addMenuItem($leftMenu, array('label' => 'join a service', 'ajaxUrl' => $oppJoinAjaxUrl,'url' => $oppJoinUrl));

                    break;
                }
            }

            $isTransitMenu = TRUE;
            $menuManager->addMenu(self::LEFTMENU, $leftMenu);
        }       

        //render workingteam of services' navigation menu  
        $menuManager->addMenuItem($leftMenu, array('label' => 'My Working Services'));

        $services = array();
        $wadmin_services = $app->getCurrentUser()->getCurrentUserServices(BUser::WORKTEAMADMINROLE);
        $sadmin_services = $app->getCurrentUser()->getCurrentUserServices(BUser::SERVEDTEAMADMINROLE);
        $wmber_services = $app->getCurrentUser()->getCurrentUserServices(BUser::WORKTEAMMEMBERROLE);
        $smber_services = $app->getCurrentUser()->getCurrentUserServices(BUser::SERVEDTEAMMEMBERROLE);
        $serviceAdmin_services = $app->getCurrentUser()->getCurrentUserServices(BBasicRolesTemplate::SERVICE_ADMIN_ROLE);
        //      $serviceMember_services = $app->getCurrentUser()->getCurrentUserServices(BBasicRolesTemplate::SERVEDTEAM_MEMBER_ROLE);

        foreach ($wadmin_services as $key => $value) {
            $services[$key] = $value;
        }

        foreach ($wmber_services as $key => $value) {
            $services[$key] = $value;
        }

        foreach ($sadmin_services as $key => $value) {
            $services[$key] = $value;
        }

        foreach ($serviceAdmin_services as $key => $value) {
            $services[$key] = $value;
        }

        /*
          foreach ($serviceMember_services as $key => $value) {
          $services[$key] = $value;
          }
         * 
         */

        foreach ($services as $service) {
            $this->addServiceMenuItem($leftMenu, $service, BService::WORKTEAMTYPE);
        }

        //render servedteams' navigation menu
        $menuManager->addMenuItem($leftMenu, array('label' => 'My Joined Services'));

        $idList = array();

        foreach ($services as $service) {
            array_push($idList, $service->getId());
        }

        foreach ($smber_services as $service) {
            $sId = $service->getId();
            if (!in_array($sId, $idList))
                $this->addServiceMenuItem($leftMenu, $service, BService::SERVEDTEAMTYPE);
        }

        $menuManager->addMenu(self::LEFTMENU, $leftMenu);
    }

    protected function addServiceMenuItem(&$menu, $service, $type) {
        $menuManager = $this->getMenuManager();
        if ($service->getVisible()) {
            $menuItem = array();
            $menuItem['label'] = $service->getName();
            $menuItem['url'] = $service->getServiceEngine()->getUIManager()->getUrl(array('rtp' => $type));
            $menuItem['ajaxUrl'] = $service->getServiceEngine()->getUIManager()->getUrl(array('ajaxLink' => array('name' => $service->getName(), 'ajaxOptions' => array('beforeSend' => $this->myServicesLinkBeforeSend))));
            //$url = $menuItem['url'];
            //$menuItem['url'] = $this->addTeamTypeIntoUrL($url, $type);
            $menuManager->addMenuItem($menu, $menuItem);
        }
    }

    protected function addTeamTypeIntoUrL($url, $type) {
        //add a session variable for role type
    }

    public static function detectDevice() {

        $iPod = stripos($_SERVER['HTTP_USER_AGENT'], "iPod");
        $iPhone = stripos($_SERVER['HTTP_USER_AGENT'], "iPhone");
        $iPad = stripos($_SERVER['HTTP_USER_AGENT'], "iPad");
        if (stripos($_SERVER['HTTP_USER_AGENT'], "Android") && stripos($_SERVER['HTTP_USER_AGENT'], "mobile")) {
            $Android = true;
        } else if (stripos($_SERVER['HTTP_USER_AGENT'], "Android")) {
            $Android = false;
            $AndroidTablet = true;
        } else {
            $Android = false;
            $AndroidTablet = false;
        }
        $webOS = stripos($_SERVER['HTTP_USER_AGENT'], "webOS");
        $BlackBerry = stripos($_SERVER['HTTP_USER_AGENT'], "BlackBerry");
        $RimTablet = stripos($_SERVER['HTTP_USER_AGENT'], "RIM Tablet");

        if ($iPhone) {
            return BUIApp::DEVICE_IPHONE;
        }

        if ($iPad) {
            return BUIApp::DEVICE_IPAD;
        }

        if ($AndroidTablet) {
            return BUIApp::DEVICE_ANDROID_TABLET;
        }

        if ($Android)
            return BUIApp::DEVICE_ANDROID;

        if ($iPod || $BlackBerry || $Android || $webOS) {
            return BUIApp::DEVICE_MOBILE_GENERAL;
        }

        if ($RimTablet)
            return BUIApp::DEVICE_TABLET_GENERAL;


        $mobile_browser = '0';

        if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
            $mobile_browser++;
        }

        if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
            $mobile_browser++;
        }

        $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
        $mobile_agents = array(
            'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
            'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
            'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
            'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
            'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
            'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
            'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
            'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
            'wapr', 'webc', 'winw', 'winw', 'xda ', 'xda-');

        if (in_array($mobile_ua, $mobile_agents)) {
            $mobile_browser++;
        }

        if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'OperaMini') > 0) {
            $mobile_browser++;
        }

        if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') > 0) {
            $mobile_browser = 0;
        }

        if ($mobile_browser > 0) {
            return BUIApp::DEVICE_MOBILE_GENERAL;
        }

        return FALSE;
    }

    public function getUrl($data = NULL) {

        $ajaxUrl = $this->getAjaxUrl($data);

        if ($ajaxUrl != NULL)
            return $ajaxUrl;

        if (isset($data['type']) && $data['type'] == 'string')
            return yii::app()->createUrl('site/index');

        return array('site/index');
    }

    public function getHomeUrl($data) {

        $currentUser = Blyn::app()->getCurrentUser();

        $personalService = $currentUser->getPersonalService();

        $url = $personalService->getUIManager()->getUrl($data);

        return $url;
    }

    public function refreshLeftMenu($screen = NULL) {
        if ($screen == NULL)
            $screen = Blyn::app()->getCurrentNode()->getUIManager()->getCurrentScreen();

        Blyn::app()->getCurrentUser()->resetTransitVariable(BUser::TransitVariable_UserServicesOfRoleType);
        //$this->registerMenu($event);

        $screen->addRenderView('refreshLeftMenu', 'refreshLeftMenu', array('screen' => $screen));
    }

}

?>
